// $Id: oaxaca.js 226 2013-07-24 05:14:16Z alan.watson.f $

function milliseconds() {
  var d = new Date();
  return d.valueOf();
}

var refreshimageinterval = 1000;

function refreshimage(id, src)
{
  var query = src.indexOf("?") != -1;
  var parameter = 0;
  var handler = function () {
    var start = milliseconds();
    if ($("img#" + id).attr("complete")) {
      $("img#" + id).attr("src", src + (query ? "&" : "?") + parameter);
    }
    ++parameter;
    var end = milliseconds();
    var wait = Math.max(0, refreshimageinterval - (end - start));
    setTimeout(handler, wait);
  };
  handler();
}

var refreshhtmlinterval = 1000;

function refreshhtml(id, src, data) 
{
  var query = src.indexOf("?") != -1;
  var parameter = 0;
  var handler = function () {
    var start = milliseconds();
    $.ajax({
      type: "POST",
      url: src + (query ? "&" : "?") + parameter,
      data: data,
      dataType: "html",
      success: function (data, html, request) {
        $("div#" + id).html(data);
      },
      complete: function (request, html) {
        ++parameter;
        var end = milliseconds();
        var interval = Math.max (0, refreshhtmlinterval - (end - start));
        setTimeout(handler, interval);
      }
    });
  }
  handler();  
}

var refreshpopupinterval;

function refreshpopup(id, src, data) 
{
  refreshpopupinterval = 1000;
  var query = src.indexOf("?") != -1;
  var parameter = 0;
  var handler = function () {
    var start = milliseconds();
    $.ajax({
      type: "POST",
      url: src + (query ? "&" : "?") + parameter,
      data: data,
      dataType: "html",
      success: function (data, html, request) {
        $("div#" + id).html(data);
      },
      complete: function (request, html) {
        ++parameter;
        if (refreshpopupinterval != 0) {
          var end = milliseconds();
          var interval = Math.max (0, refreshhtmlinterval - (end - start));
          setTimeout(handler, interval);
        }
      }
    });
  }
  handler();  
}

function stoprefreshingpopup () {
  refreshpopupinterval = 0;
}

function sh(command, mustconfirm) {
  if (mustconfirm == "" || confirm("Do you want to " + mustconfirm + "?\n")) {
    $.ajax({
      type: "POST",
      url: "sh",
      data: command,
      dataType: "text",
      success: function (data, status, request) {
        if (data != "") {
          alert(data);
        }
      }
    });
  }
  return false;
}

function scm(command, mustconfirm) {
  if (mustconfirm == "" || confirm("Do you want to " + mustconfirm + "?\n")) {
    $.ajax({
      type: "POST",
      url: "scm",
      data: command,
      dataType: "text",
      success: function (data, status, request) {
        if (data != "") {
          alert(data);
        }
      },
      error: function (data, status, error) {
        alert("server error: " + status + " (" + error + ").");
      }
    });
  }
  return false;
}
